//
//  QGHelpPageViewController.m
//  QuanGou
//
//  Created by lanou3g on 15/11/17.
//  Copyright © 2015年 DongYongFei. All rights reserved.
//

#import "QGHelpPageViewController.h"
#import "QGHelpPageTableViewCell.h"
#import "QGHelpPageModel.h"
#import <CoreLocation/CoreLocation.h>
#import "QGHelpDetailViewController.h"
#import "QGCityListViewController.h"


@interface QGHelpPageViewController ()<UITableViewDelegate,UITableViewDataSource,QGCityListDelegate>
@property (weak, nonatomic) IBOutlet UIImageView *head_bg_ImageView;
@property (weak, nonatomic) IBOutlet UIButton *cityButton;


@property (weak, nonatomic) IBOutlet UITableView *listTableView;


@property (nonatomic, strong) NSMutableArray *sourceArray;

@end

@implementation QGHelpPageViewController

static QGHelpPageViewController *s_defaultManager = nil;

- (void)viewDidLoad {
    [super viewDidLoad];
    self.sourceArray = [NSMutableArray array];
    
    self.head_bg_ImageView.userInteractionEnabled = YES;
    
    [self.listTableView registerNib:[UINib nibWithNibName:@"QGHelpPageTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"QGHelpPageTableViewCell"];
    
    AVQuery *queryLocation = [AVQuery queryWithClassName:@"UserModel"];
    [queryLocation whereKey:@"userId" equalTo:[AVUser currentUser].objectId];
    
    [self.cityButton setTitle:[queryLocation getFirstObject][@"locationCity"] forState:(UIControlStateNormal)];
    
    
    AVGeoPoint *currenUserLocation = [queryLocation getFirstObject][@"location"];
    
    
    [self requestDataWithlatitude:currenUserLocation.latitude longitude:currenUserLocation.longitude];
   
}

- (void)requestDataWithlatitude:(double)latitude longitude:(double)longitude{
    
   
    
    AVQuery *query = [AVQuery queryWithClassName:@"HelpSendModel"];
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        if (!error) {
            
             [self.sourceArray removeAllObjects];
            
            for (AVObject *obj in objects) {
                NSMutableDictionary *dic = [NSMutableDictionary dictionary];
                int i = 0;
                for (NSString *key in obj.allKeys) {

                    [dic setValue:obj[obj.allKeys[i]] forKey:key];
                    i++;
                }
                [dic setValue:obj.createdAt forKey:@"creteTime"];
                
                AVGeoPoint *point = dic[@"location"];
                //第一个坐标
                CLLocation *current=[[CLLocation alloc] initWithLatitude:point.latitude longitude:point.longitude];
                //第二个坐标
                CLLocation *before=[[CLLocation alloc] initWithLatitude:latitude longitude:longitude];
                // 计算距离
                CLLocationDistance meters = [current distanceFromLocation:before];
                
                AVQuery *queryUserico = [AVQuery queryWithClassName:@"UserModel"];
                [queryUserico whereKey:@"userId" equalTo:dic[@"userId"]];
                
                QGHelpPageModel *helpPageModel = [[QGHelpPageModel alloc] init];
                
                [queryUserico getFirstObjectInBackgroundWithBlock:^(AVObject *object, NSError *error) {
                    AVFile *usericoFile = object[@"userico"];
                    helpPageModel.userico = usericoFile.url;
                    helpPageModel.userName = object[@"userName"];
                    helpPageModel.sex = object[@"sex"];
                    
                    helpPageModel.distance = [NSString stringWithFormat:@"%.2f KM",meters / 1000];
                    [helpPageModel setValuesForKeysWithDictionary:dic];
                    
                    [self.sourceArray addObject:helpPageModel];
                    [self.listTableView reloadData];
                }];
            }
        }else{
            NSLog(@"查询出错 %s %d",__FUNCTION__,__LINE__);
        }
        
    }];

}
- (IBAction)changeCityButton:(UIButton *)sender {
    QGCityListViewController *cityListVC = [[QGCityListViewController alloc] initWithNibName:@"QGCityListViewController" bundle:[NSBundle mainBundle]];
    cityListVC.cityListDelegate = self;
    [self showViewController:cityListVC sender:nil];
}
- (void)cityName:(NSString *)city latitude:(double)latitude longitude:(double)longitude {
    
    [self.cityButton setTitle:city forState:(UIControlStateNormal)];
    [self requestDataWithlatitude:latitude longitude:longitude];
    
}


#pragma mark tableView Delegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 80;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.sourceArray.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    QGHelpPageTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"QGHelpPageTableViewCell" forIndexPath:indexPath];
    cell.helpPageModel = self.sourceArray[indexPath.row];
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    QGHelpDetailViewController *helpDetailVC = [[QGHelpDetailViewController alloc] initWithNibName:@"QGHelpDetailViewController" bundle:[NSBundle mainBundle]];
    helpDetailVC.helpPageModel = self.sourceArray[indexPath.row];
    [self presentViewController:helpDetailVC animated:YES completion:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
